package web.classes;

import interfaces.GUIVisitor;
import java.util.Vector;
import domain.items.Item;
import domain.items.PostPacket;
import domain.items.ThreadPacket;
import domain.items.TopicPacket;
import domain.users.User;
import jaxcent.HtmlBold;
import jaxcent.HtmlButton;
import jaxcent.HtmlDiv;
import jaxcent.HtmlImage;
import jaxcent.HtmlInputButton;
import jaxcent.HtmlInputPassword;
import jaxcent.HtmlInputRadio;
import jaxcent.HtmlInputText;
import jaxcent.HtmlTable;
import jaxcent.HtmlTextArea;
import jaxcent.JaxcentPage;
import jaxcent.Jaxception;

public class AjaxIndex extends JaxcentPage implements GUIVisitor {

	private WebHandler _handler = new WebHandler();

	private Vector<HtmlDiv> htmlDivTable;

	/***************************************************************************
	 * Html Divisions
	 **************************************************************************/
	HtmlDiv loadDiv = new HtmlDiv(this, "loading");
	HtmlDiv mainDiv = new HtmlDiv(this, "mainDiv");
	HtmlDiv loginDiv = new HtmlDiv(this, "loginDiv");
	HtmlDiv registerDiv = new HtmlDiv(this, "registerDiv");
	HtmlDiv searchDiv = new HtmlDiv(this, "searchDiv");
	HtmlDiv searchAuthorDiv = new HtmlDiv(this, "searchAuthorDiv");
	HtmlDiv searchDateDiv = new HtmlDiv(this, "searchDateDiv");
	HtmlDiv searchContentDiv = new HtmlDiv(this, "searchContentDiv");
	HtmlDiv messageDiv = new HtmlDiv(this, "messageDiv");
	HtmlDiv userActionDiv = new HtmlDiv(this, "userActionDiv");
	HtmlDiv updateDiv = new HtmlDiv(this, "updateDiv");
	HtmlDiv statDiv = new HtmlDiv(this, "statDiv");
	HtmlDiv statResultDiv = new HtmlDiv(this,"statResultDiv");

	/***************************************************************************
	 * Main View Elements
	 **************************************************************************/
	HtmlImage logo = new HtmlImage(this, "logo") {
		public void onClick() {
			try {
				updateMainView(_handler.getRootTopic());
				showButtons();
				refreshStatus();
				showDiv("mainDiv");
			} catch (Jaxception e) {
				System.out.println(e.getMessage());
			}
		}
	};
	HtmlBold welcome = new HtmlBold(this, "welcome");
	HtmlButton loginButt = new HtmlButton(this, "login") {
		public void onClick() {
			try {
				showDiv("loginDiv");
			} catch (Jaxception e) {
				System.out.println(e.getMessage());
			}
		}
	};
	HtmlButton registerButt = new HtmlButton(this, "register") {
		public void onClick() {
			try {
				showDiv("registerDiv");
			} catch (Jaxception e) {
				System.out.println(e.getMessage());
			}
		}
	};
	HtmlButton searchButt = new HtmlButton(this, "search") {
		public void onClick() {
			try {
				showDiv("searchDiv");
			} catch (Jaxception e) {
				System.out.println(e.getMessage());
			}
		}
	};
	HtmlButton logoutButt = new HtmlButton(this, "logout") {
		public void onClick() {
			_handler.logout();
			try {
				updateMainView(_handler.getCurrentlyViewedItem());
				welcome.setInnerHTML("Hello Guest!");
				refreshStatus();
			} catch (Jaxception e) {
				System.out.println(e.getMessage());
			}
		}
	};
	HtmlButton addmsgButt = new HtmlButton(this, "addmsg") {
		public void onClick() {
			try {
				messageAction.setInnerHTML("Add a New Message :");
				showDiv("messageDiv");
			} catch (Jaxception e) {
				System.out.println(e.getMessage());
			}
		}
	};
	HtmlButton replymsgButt = new HtmlButton(this, "replymsg") {
		public void onClick() {
			try {
				messageAction.setInnerHTML("Add a Reply Message :");
				showDiv("messageDiv");
			} catch (Jaxception e) {
				System.out.println(e.getMessage());
			}
		}
	};
	HtmlButton updateButt = new HtmlButton(this, "update") {
		public void onClick() {
			try {
				updateUsername.setInnerHTML(_handler.getUsername());
				updateOldPass.setValue("");
				updateEmail.setValue("");
				updateNewPass1.setValue("");
				updateNewPass2.setValue("");
				showDiv("updateDiv");
			} catch (Jaxception e) {
				System.out.println(e.getMessage());
			}
		}
	};
	HtmlButton statisticButt = new HtmlButton(this, "statistic") {
		public void onClick() {
			try {
				showDiv("statDiv");
			} catch (Jaxception e) {
				System.out.println(e.getMessage());
			}
		}
	};
	HtmlButton promoteButt = new HtmlButton(this, "promote") {
		public void onClick() {
			try {
				userActionTitle.setInnerHTML("Promote");
				userActionButt.setInnerHTML("Promote User");
				showDiv("userActionDiv");
			} catch (Jaxception e) {
				System.out.println(e.getMessage());
			}
		}
	};
	HtmlButton demoteButt = new HtmlButton(this, "demote") {
		public void onClick() {
			try {
				userActionTitle.setInnerHTML("Demote");
				userActionButt.setInnerHTML("Demote User");
				showDiv("userActionDiv");
			} catch (Jaxception e) {
				System.out.println(e.getMessage());
			}
		}
	};
	HtmlButton deleteuserButt = new HtmlButton(this, "deleteuser") {
		public void onClick() {
			try {
				userActionTitle.setInnerHTML("Delete");
				userActionButt.setInnerHTML("Delete User");
				showDiv("userActionDiv");
			} catch (Jaxception e) {
				System.out.println(e.getMessage());
			}
		}
	};
	HtmlInputButton backButt = new HtmlInputButton(this, "backButt") {
		public void onClick() {
			try {
				updateMainView(_handler.getFather());
				showButtons();
				refreshStatus();
			} catch (Jaxception e) {
				System.out.println(e.getMessage());
			}
		}
	};
	HtmlBold status = new HtmlBold(this, "status");
	HtmlTable mainView = new HtmlTable(this, "myTable");

	/***************************************************************************
	 * Login Elements
	 **************************************************************************/
	HtmlInputText loginNameInput = new HtmlInputText(this, "loginNameInput");
	HtmlInputPassword loginPassInput = new HtmlInputPassword(this,"loginPassInput");
	HtmlButton loginOkButt = new HtmlButton(this, "loginOkButt") {
		public void onClick() {
			try {
				String name = loginNameInput.getValue();
				String password = loginPassInput.getValue();
				User user = _handler.login(name, password);
				loginNameInput.setValue("");
				loginPassInput.setValue("");
				if (user != null) {
					updateWelcome();
					refreshStatus();
					showDiv("mainDiv");
					showButtons();
				} else {
					popup("Authentication failure!\nCheck username and password!");
				}
			} catch (Jaxception e) {
				System.out.println(e.getMessage());
			}
		}
	};
	HtmlButton loginCancelButt = new HtmlButton(this, "loginCancelButt") {
		public void onClick() {
			try {
				loginNameInput.setValue("");
				loginPassInput.setValue("");
				showDiv("mainDiv");
				refreshStatus();
			} catch (Jaxception e) {
				System.out.println(e.getMessage());
			}
		}
	};

	/***************************************************************************
	 * Register Elements
	 **************************************************************************/
	HtmlInputText registerNameInput = new HtmlInputText(this,"registerNameInput");
	HtmlInputPassword registerPassInput = new HtmlInputPassword(this,"registerPassInput");
	HtmlInputText registerEmailInput = new HtmlInputText(this,"registerEmailInput");
	HtmlButton registerOkButt = new HtmlButton(this, "registerOkButt") {
		public void onClick() {
			try {
				String username = registerNameInput.getValue();
				String password = registerPassInput.getValue();
				String email = registerEmailInput.getValue();
				boolean succ = _handler.registerUser(username, email, password);
				registerNameInput.setValue("");
				registerPassInput.setValue("");
				registerEmailInput.setValue("");
				if (succ) {
					_handler.login(username, password);
					updateWelcome();
					showButtons();
					refreshStatus();
					showDiv("mainDiv");
				} else {
					popup("Registration failure!\nFollow registration instructions!");
				}
			} catch (Jaxception e) {
				System.out.println(e.getMessage());
			}
		}
	};
	HtmlButton registerCancelButt = new HtmlButton(this, "registerCancelButt") {
		public void onClick() {
			try {
				registerNameInput.setValue("");
				registerPassInput.setValue("");
				registerEmailInput.setValue("");
				showButtons();
				refreshStatus();
				showDiv("mainDiv");
			} catch (Jaxception e) {
				System.out.println(e.getMessage());
			}
		}
	};

	/***************************************************************************
	 * Search Elements
	 **************************************************************************/
	HtmlButton searchAuthorButt = new HtmlButton(this, "searchAuthorButt") {
		public void onClick() {
			try {
				showDiv("searchAuthorDiv");
			} catch (Jaxception e) {
				System.out.println(e.getMessage());
			}
		}
	};
	HtmlButton searchDateButt = new HtmlButton(this, "searchDateButt") {
		public void onClick() {
			try {
				showDiv("searchDateDiv");
			} catch (Jaxception e) {
				System.out.println(e.getMessage());
			}
		}
	};
	HtmlButton searchContentButt = new HtmlButton(this, "searchContentButt") {
		public void onClick() {
			try {
				showDiv("searchContentDiv");
			} catch (Jaxception e) {
				System.out.println(e.getMessage());
			}
		}
	};
	HtmlButton searchCancelButt = new HtmlButton(this, "searchCancelButt") {
		public void onClick() {
			try {
				showDiv("mainDiv");
			} catch (Jaxception e) {
				System.out.println(e.getMessage());
			}
		}
	};

	/***************************************************************************
	 * Search by Author Elements
	 **************************************************************************/
	HtmlInputText searchAuthorInput = new HtmlInputText(this,"searchAuthorInput");
	HtmlButton searchAuthor = new HtmlButton(this, "searchAuthor") {
		public void onClick() {
			try {
				String author = searchAuthorInput.getValue();
				if (author.equals("")) {
					popup("Error during Serach - missing input!");
				} else {
					_handler.searchByAuthor(author);
					searchAuthorInput.setValue("");
					updateMainView(_handler.getCurrentlyViewedItem());
					refreshStatus();
					showDiv("mainDiv");
				}
			} catch (Jaxception e) {
				System.out.println(e.getMessage());
			}
		}
	};
	HtmlButton searchAuthorCancelButt = new HtmlButton(this,"searchAuthorCancelButt"){
		public void onClick() {
			try {
				searchAuthorInput.setValue("");
				refreshStatus();
				showDiv("mainDiv");
			} catch (Jaxception e) {
				System.out.println(e.getMessage());
			}
		}
	};

	/***************************************************************************
	 * Search by Date Elements
	 **************************************************************************/
	HtmlInputText searchDateFrom = new HtmlInputText(this, "searchDateFrom");
	HtmlInputText searchDateTo = new HtmlInputText(this, "searchDateTo");
	HtmlButton searchDate = new HtmlButton(this, "searchDate") {
		public void onClick() {
			try {
				String fromDate = searchDateFrom.getValue();
				String toDate = searchDateTo.getValue();
				_handler.searchByDate(fromDate, toDate);
				searchDateFrom.setValue("");
				searchDateTo.setValue("");
				updateMainView(_handler.getCurrentlyViewedItem());
				refreshStatus();
				showDiv("mainDiv");
			} catch (Jaxception e) {
				System.out.println(e.getMessage());
			}
		}
	};
	HtmlButton searchDateCancelButt = new HtmlButton(this,
			"searchDateCancelButt") {
		public void onClick() {
			try {
				searchDateFrom.setValue("");
				searchDateTo.setValue("");
				refreshStatus();
				showDiv("mainDiv");
			} catch (Jaxception e) {
				System.out.println(e.getMessage());
			}
		}
	};

	/***************************************************************************
	 * Search by Content Elements
	 **************************************************************************/
	HtmlTextArea searchContentInput = new HtmlTextArea(this,"searchContentInput");
	HtmlButton searchContent = new HtmlButton(this, "searchContent") {
		public void onClick() {
			try {
				String content = searchContentInput.getValue();
				if (content.equals("")) {
					popup("Error during Serach - missing input!");
				} else {
					_handler.searchByContent(content);
					searchContentInput.setValue("");
					updateMainView(_handler.getCurrentlyViewedItem());
					refreshStatus();
					showDiv("mainDiv");
				}
			} catch (Jaxception e) {
				System.out.println(e.getMessage());
			}
		}
	};
	HtmlButton searchContentCancelButt = new HtmlButton(this,
			"searchContentCancelButt") {
		public void onClick() {
			try {
				searchContentInput.setValue("");
				refreshStatus();
				showDiv("mainDiv");
			} catch (Jaxception e) {
				System.out.println(e.getMessage());
			}
		}
	};

	/***************************************************************************
	 * Message related Elements
	 **************************************************************************/
	HtmlBold messageAction = new HtmlBold(this, "messageAction");
	HtmlInputText messageSubject = new HtmlInputText(this, "messageSubject");
	HtmlTextArea messageText = new HtmlTextArea(this, "messageText");
	HtmlButton messageApply = new HtmlButton(this, "messageApply") {
		public void onClick() {
			try {
				String subject = messageSubject.getValue();
				String text = messageText.getValue();
				if (validSubject(subject) && validText(text)) {
					String action = messageAction.getInnerHTML();
					if (action.equals("Add a New Message :")) {
						_handler.addThread(subject, text);
					} else if (action.equals("Add a Reply Message :")) {
						_handler.addPost(subject, text);
					} else {
						if (action.equals("Modify Message :")) {
							_handler.updatePost(subject, text);
							updateMainView(_handler.getFather());
							showButtons();
							refreshStatus();
						}
					}
					messageSubject.setValue("");
					messageText.setValue("");
					updateMainView(_handler.getCurrentlyViewedItem());
					refreshStatus();
					showDiv("mainDiv");
				} else {
					popup("Input is missing or invalid!");
				}
			} catch (Jaxception e) {
				System.out.println(e.getMessage());
			}
		}

		private boolean validText(String text) {
			return !(text.equals(""));
		}

		private boolean validSubject(String subject) {
			return !(subject.equals(""));
		}
	};
	HtmlButton messageCancel = new HtmlButton(this, "messageCancel") {
		public void onClick() {
			try {
				messageSubject.setValue("");
				messageText.setValue("");
				updateMainView(_handler.getFather());
				refreshStatus();
				showDiv("mainDiv");
			} catch (Jaxception e) {
				System.out.println(e.getMessage());
			}
		}
	};

	/***************************************************************************
	 * Update-Details related Elements
	 **************************************************************************/
	HtmlBold updateUsername = new HtmlBold(this, "updateUsername");
	HtmlInputPassword updateOldPass = new HtmlInputPassword(this,"updateOldPass");
	HtmlInputText updateEmail = new HtmlInputText(this, "updateEmail");
	HtmlInputPassword updateNewPass1 = new HtmlInputPassword(this,"updateNewPass1");
	HtmlInputPassword updateNewPass2 = new HtmlInputPassword(this,"updateNewPass2");
	HtmlButton updateSave = new HtmlButton(this, "UpdateSaveButt") {
		public void onClick() {
			try {
				if (!(updateNewPass1.getValue().equals(updateNewPass2
						.getValue()))) {
					popup("New password & confirmation does not match!");
				} else {
					boolean success = _handler
							.updateUser(_handler.getUsername(), updateEmail
									.getValue(), updateOldPass.getValue(),
									updateNewPass1.getValue());
					if (success) {
						popup("Details updated successfully!");
						refreshStatus();
						showDiv("mainDiv");
					} else {
						popup("Could not update details - some input missing or invalid!");
					}
				}
			} catch (Jaxception e) {
				System.out.println(e.getMessage());
			}
		}
	};
	HtmlButton updateCancel = new HtmlButton(this, "UpdateCancelButt") {
		public void onClick() {
			try {
				refreshStatus();
				showDiv("mainDiv");
			} catch (Jaxception e) {
				System.out.println(e.getMessage());
			}
		}
	};

	/****************************************************************************
	 * User Action related Elements
	 ***************************************************************************/
	HtmlBold userActionTitle = new HtmlBold(this, "userActionTitle");
	HtmlInputText userActionInput = new HtmlInputText(this, "userActionInput");
	HtmlButton userActionButt = new HtmlButton(this, "userActionButt") {
		public void onClick() {
			try {
				String action = userActionTitle.getInnerHTML();
				String username = userActionInput.getValue();
				boolean succ = false;
				if (username.equals("")) {
					popup("Could not "+action+" user - missing user name!");
				} else {	
					if (action.equals("Promote")) {
						succ = _handler.promoteUser(username);
					} else if (action.equals("Demote")) {
						succ = _handler.demoteUser(username);
					} else if (action.equals("Delete")) {
						succ = _handler.deleteUser(username);
					}
					if(succ){
						popup("The user \""+username+"\" was "+action+"d successfully!");
						userActionInput.setValue("");
						showButtons();
						refreshStatus();
						showDiv("mainDiv");
					}
					else{
						popup("Could not "+action+" the user \""+username+"\"!");
						userActionInput.setValue("");
					}	
				}
			} catch (Jaxception e) {
				System.out.println(e.getMessage());
			}
		}
	};
	HtmlButton userActionCancel = new HtmlButton(this, "userActionCancel") {
		public void onClick() {
			try {
				userActionInput.setValue("");
				showButtons();
				refreshStatus();
				showDiv("mainDiv");
			} catch (Jaxception e) {
				System.out.println(e.getMessage());
			}
		}
	};

	/****************************************************************************
	 * Statistic related Elements
	 ***************************************************************************/
	HtmlInputRadio stat1 = new HtmlInputRadio(this, "stat1");
	HtmlInputRadio stat2 = new HtmlInputRadio(this, "stat2");
	HtmlInputRadio stat3 = new HtmlInputRadio(this, "stat3");
	HtmlInputText statInput = new HtmlInputText(this, "statInput");
	HtmlButton statSubmit = new HtmlButton(this, "statSubmit"){
		public void onClick() {
			try {
				if (stat1.getChecked()) {
					String username = statInput.getValue();
					if (username.equals("")) {
						popup("Could not display result - missing user name!");
						return;
					} else {
						statInput.setValue("");
						_handler.getStatForUser(username);
						statGraph.setSrc("stat1"+username+".jpg");
					}
				}else if(stat2.getChecked()){
					_handler.getStat_PostHours();	
					statGraph.setSrc("stat2.jpg");
				}else if(stat3.getChecked()){
					_handler.getStat_UserHours();	
					statGraph.setSrc("stat3.jpg");
				}else{
					popup("Can't you read?\nChoose the type of Statistical Graph to display!");
					return;
				}	

				showDiv("statResultDiv");
				
			} catch (Jaxception e) {
				System.out.println(e.getMessage());
			}
		}
	};
	HtmlButton statCancel = new HtmlButton(this, "statCancel"){
		public void onClick() {
			try {
				stat1.setChecked(false);
				stat2.setChecked(false);
				stat3.setChecked(false);
				statInput.setValue("");
				refreshStatus();
				showDiv("mainDiv");
			} catch (Jaxception e) {
				System.out.println(e.getMessage());
			}
		}
	};
	
	/****************************************************************************
	 * Statistic result Chart related Elements
	 ***************************************************************************/
	HtmlImage statGraph = new HtmlImage(this,"statGraph");
	HtmlButton statReturnButt = new HtmlButton(this,"statReturnButt"){
		public void onClick() {
			try {
				updateMainView(_handler.getRootTopic());
				showButtons();
				refreshStatus();
				showDiv("mainDiv");
			} catch (Jaxception e) {
				System.out.println(e.getMessage());
			}
		}
	};

	/**
	 * Constructor
	 */
	public AjaxIndex() {
		super();
		System.out.println("new web client arrived!");
		this.htmlDivTable = new Vector<HtmlDiv>();
		initDivTable();
	}

	private void initDivTable() {
		this.htmlDivTable.add(this.mainDiv);
		this.htmlDivTable.add(this.loginDiv);
		this.htmlDivTable.add(this.registerDiv);
		this.htmlDivTable.add(this.searchDiv);
		this.htmlDivTable.add(this.searchAuthorDiv);
		this.htmlDivTable.add(this.searchDateDiv);
		this.htmlDivTable.add(this.searchContentDiv);
		this.htmlDivTable.add(this.messageDiv);
		this.htmlDivTable.add(this.userActionDiv);
		this.htmlDivTable.add(this.updateDiv);
		this.htmlDivTable.add(this.statDiv);
		this.htmlDivTable.add(this.statResultDiv);
	}

	public void onLoad() {
		try {
			showDiv("mainDiv");
			this.loadDiv.hide();
			showButtons();
			updateMainView(this._handler.getRootTopic());
			refreshStatus();
		} catch (Jaxception e1) {
			System.out.println(e1.getMessage());
		}
	}

	public void onUnload() {
		this._handler.sayGoodbye();
	}

	private void updateWelcome() throws Jaxception {
		String welcomeTag = "Hello " + _handler.getUsername() + "!";
		switch (_handler.getUserRank()) {
		case 1:
			welcomeTag += " (Member)";
			break;
		case 2:
			welcomeTag += " (Moderator)";
			break;
		case 3:
			welcomeTag += " (Administrator)";
			break;
		case 4:
			welcomeTag += " (Master Splinter)";
			break;
		}
		welcome.setInnerHTML(welcomeTag);
	}

	public void createItemsView(TopicPacket topics) {

		Vector<String> topicsNames = topics.getSubItems();
		try {
			mainView.deleteAllRows();
			if (topicsNames.size() == 0) {
				this.showEmptyMainView();
			} else {
				for (int i = 0; i < topicsNames.size(); i++) {
					final int index = i + 1;
					String buttonName = "topic" + index;
					mainView
							.insertRow(
									i,
									new String[] { "<center><big><b id=\""
											+ buttonName
											+ "\" style=\"width:100%; height: 50px;\" >"
											+ topicsNames.elementAt(i)
											+ "</b></big></center>" });
					new HtmlBold(this, buttonName) {
						public void onClick() {
							try {
								updateMainView(_handler.getItem(index));
								refreshStatus();
							} catch (Jaxception e) {
								System.out.println(e.getMessage());
							}
						}
					};
				}
			}
		} catch (Jaxception e) {
			System.out.println(e.getMessage());
		}
	}

	public void createItemsView(ThreadPacket thread) {
		Vector<PostPacket> tPosts = thread.getPosts();
		try {
			mainView.deleteAllRows();
			if (tPosts.size() == 0) {
				showEmptyMainView();
			} else {
				int index = 1;
				String[][] atrr = new String[2][1];
				String[][] val = new String[2][1];
				atrr[0][0] = "width";
				val[0][0] = "25%";

				mainView.deleteAllRows();
				for (PostPacket postPacket : tPosts) {
					String[] postView = createPost(index, postPacket);
					this.mainView.insertRow(index - 1, postView, atrr, val);
					if (postPacket.getScore().equals("")) {
						makeButtonsAction(index, postPacket.getOwner());
					}
					index++;
				}
			}
		} catch (Jaxception e) {
			System.out.println(e.getMessage());
		}

	}

	private void showEmptyMainView() throws Jaxception {
		String[] content = new String[1];
		String[][] atrr = new String[1][1];
		String[][] val = new String[1][1];
		content[0] = "<th><big><b>&nbsp;</font></b></th>";
		atrr[0][0] = "height";
		val[0][0] = "50px";
		this.mainView.insertRow(0, content, atrr, val);

	}

	private String[] createPost(int index, PostPacket postPacket) {

		int rank = this._handler.getUserRank();
		String[] tPost = new String[2];
		tPost[0] = "<th>" + "<p>Posted by <font color=\"blue\">"
				+ postPacket.getOwner() + "</font><br/>At "
				+ postPacket.getDate() + "<br/><br/>";
		if (rank > 1 && postPacket.getScore().equals("")) {
			// show both buttons (delete/modify)
			tPost[0] = tPost[0] + addPostButtons(index, true);
		} else if (rank > 0
				&& postPacket.getOwner().equals(this._handler.getUsername())
				&& postPacket.getScore().equals("")) {
			// show only modify button
			tPost[0] = tPost[0] + addPostButtons(index, false);
		} else if (!postPacket.getScore().equals("")) {
			// show none of the buttons, show score if this is a search result
			// post
			tPost[0] += "score: " + postPacket.getScore();
		}
		tPost[0] = tPost[0] + "</p></th>";

		tPost[1] = "<td><u><strong>" + postPacket.getSubject()
				+ "</u></strong><br/><br/>" + postPacket.getContent() + "</td>";

		return tPost;
	}

	private void makeButtonsAction(final int index, String owner) {
		int rank = this._handler.getUserRank();
		final HtmlInputText messageSubject = new HtmlInputText(this,
				"messageSubject");
		final HtmlTextArea messageText = new HtmlTextArea(this, "messageText");
		if (rank > 1 || (rank > 0 && owner.equals(this._handler.getUsername()))) {
			new HtmlButton(this, "postModify" + index) {
				public void onClick() {
					try {
						_handler.getItem(index);
						PostPacket tPost = (PostPacket) _handler
								.getCurrentlyViewedItem();
						messageSubject.setValue(tPost.getName());
						messageText.setValue(tPost.getContent());
						messageAction.setInnerHTML("Modify Message :");
						showDiv("messageDiv");
					} catch (Jaxception e) {
						System.out.println(e.getMessage());
					}
				}
			};
		}
		if (rank > 1) {
			new HtmlButton(this, "postDelete" + index) {
				public void onClick() {
					try {
						_handler.getItem(index);
						_handler.deletePost();
						updateMainView(_handler.getFather());
						refreshStatus();
					} catch (Jaxception e) {
						System.out.println(e.getMessage());
					}
				}
			};
		}
	}

	private String addPostButtons(int index, boolean isDelete) {
		String ans = "<button id=\"postModify" + index + "\" >Modify</button>";
		if (isDelete) {
			ans = ans + "<button id=\"postDelete" + index
					+ "\" >Delete</button>";
		}
		return ans;
	}

	private void updateMainView(Item item) throws Jaxception {
		this.mainView.setVisible(false);
		item.accept(this);
		showButtons();
		this.mainView.setVisible(true);

	}

	private void showDiv(String divName) throws Jaxception {
		HtmlDiv toShow = null;
		for (HtmlDiv divElement : this.htmlDivTable) {
			if (divElement.getID().equals(divName)) {
				toShow = divElement;
			} else {
				divElement.hide();
			}
		}
		if (toShow != null) {
			toShow.show();
		} else {
			throw new Jaxception("No such div: " + divName);
		}
	}

	private void refreshStatus() throws Jaxception {
		this.status.setInnerText(this._handler.getStatus());
	}

	private void showButtons() {
		int rank = this._handler.getUserRank();
		try {
			this.logoutButt.hide();
			this.addmsgButt.hide();
			this.replymsgButt.hide();
			this.updateButt.hide();
			this.statisticButt.hide();
			this.promoteButt.hide();
			this.demoteButt.hide();
			this.deleteuserButt.hide();
			if (rank >= 1) {
				this.logoutButt.show();
				this.updateButt.show();
				if (this._handler.getCurrentlyViewedItem() instanceof ThreadPacket)
					this.replymsgButt.show();
				if (this._handler.getCurrentlyViewedItem() instanceof TopicPacket)
					this.addmsgButt.show();
			}
			if (rank >= 2) {
				this.statisticButt.show();
			}
			if (rank == 3) {
				this.promoteButt.show();
				this.demoteButt.show();
				this.deleteuserButt.show();
			}
		} catch (Jaxception e) {
			System.out.println(e.getMessage());
		}

	}

	public void popup(String message) {
		try {
			execJavaScriptCode("alert", false, new Object[] { message });
		} catch (Jaxception e) {
			System.out.println(e.getMessage());
		}
	}

}
